package com.quectel.cms.controller.sys;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.sys.SysCodeTreeDataVo;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.sys.module.sys.dto.SysCodeDto;
import com.quectel.sys.module.sys.service.SysCodeService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author yangkai
 * @date 2019-08-07 09:43:48
 */
@RestController
@RequestMapping("/sys/code")
@Tag(name = "SysCodeController", description = "系统字典相关api")
public class SysCodeController extends BaseController {

    @DubboReference
    private SysCodeService sysCodeService;

    @RequestMapping("/codeTree")
    @RequirePermissions(values = "sysCode:codeTree")
    @Operation(summary = "系统字典树")
    public Response<Object> codeTree() {
        List<SysCodeDto> sysCodeDtos = this.sysCodeService.queryCodeTree();

        List<SysCodeTreeDataVo> sysCodeTreeDataVos = treeBuilder(sysCodeDtos, 1L);
        if (CollectionUtils.isNotEmpty(sysCodeTreeDataVos) && sysCodeTreeDataVos.get(0).getChildes() != null) {
            sysCodeTreeDataVos.get(0).getChildes().forEach(v -> sortChildren(v.getChildes()));
        }

        return Response.ok().wrap(sysCodeTreeDataVos);
    }

    public static void sortChildren(List<SysCodeTreeDataVo> childrenList) {
        if (childrenList != null && childrenList.size() > 0) {
            childrenList.sort((o1, o2) -> {
                if (o1.getSort() != null && o2.getSort() != null) {
                    return o1.getSort() - o2.getSort();
                }
                return 0;
            });
            for (SysCodeTreeDataVo sysCodeDto : childrenList) {
                if (sysCodeDto.getChildes() != null) {
                    sortChildren(sysCodeDto.getChildes());
                }
            }
        }
    }

    private List<SysCodeTreeDataVo> treeBuilder(List<SysCodeDto> codeDtoList, Long rootId) {
        List<SysCodeTreeDataVo> groups = new ArrayList<>();

        List<SysCodeTreeDataVo> SysCodeTreeDataVos = CopyUtils.copyList(codeDtoList, SysCodeTreeDataVo.class);
        for (SysCodeTreeDataVo c1 : SysCodeTreeDataVos) {
            if (Objects.equals(rootId, c1.getId())) {
                groups.add(c1);
            }
            for (SysCodeTreeDataVo c2 : SysCodeTreeDataVos) {
                if (c2.getParentId().equals(c1.getId())) {
                    if (c1.getChildes() == null) {
                        c1.setChildes(new ArrayList<>());
                    }
                    c2.setParentName(c1.getName());
                    c1.getChildes().add(c2);
                }
            }
        }
        return groups;
    }

    @RequestMapping("/info/{id}")
    /*   @RequirePermissions(values ="sysCode:info")*/
    @Operation(summary = "根据ID查询系统字典")
    public Response<Object> info(@PathVariable("id") Long id) {
        SysCodeDto dto = this.sysCodeService.selectById(id);
        return Response.ok().wrap(dto);
    }

    @RequestMapping("/save")
    @RequirePermissions(values = "sysCode:edit")
    @Operation(summary = "保存系统字典")
    public Response<Object> save(@RequestBody @Validated SysCodeDto dto) {
        if (dto.getType() == 1) {
            List<SysCodeDto> entityList = this.sysCodeService.queryList(new HashMap<String, Object>() {{
                put("mark", dto.getMark());
            }});
            if (entityList != null && entityList.size() > 0) {
                return Response.error("字典标识已经存在,请重新输入!");
            }
        } else if (dto.getType() == 2) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("parentId", dto.getParentId());
            List<SysCodeDto> entityList = this.sysCodeService.queryList(queryMap);
            for (SysCodeDto sysCodeDto : entityList) {
                if (sysCodeDto.getValue().equals(dto.getValue())) {
                    return Response.error("字典值已经存在,请重新输入!");
                }
            }
        }
        this.sysCodeService.save(dto);
        SysCodeDto sysCodeDto = this.sysCodeService.selectById(dto.getId());
        return Response.ok().wrap(sysCodeDto);
    }

    @RequestMapping("/update")
    @RequirePermissions(values = "sysCode:update")
    @Operation(summary = "更新系统字典")
    public Response<Object> update(@RequestBody @Validated SysCodeDto dto) {

        if (StringUtils.isBlank(dto.getMark())) {
            dto.setMark(null);
        }
        this.sysCodeService.updateAllColumnById(dto);

        SysCodeDto sysCodeDto = this.sysCodeService.selectById(dto.getId());

        return Response.ok().wrap(sysCodeDto);
    }

    @PostMapping("delete")
    @RequirePermissions(values = "sysMenu:delete")
    @Operation(summary = "批量删除系统字典")
    public Response<Object> delete(@RequestBody Long[] ids) {
        String message = sysCodeService.deleteBatch(ids);
        return message != null ? Response.error(message) : Response.ok();
    }

    @GetMapping("selectByMark")
    @Operation(summary = "根据字典标识查询字典")
    public Response<Object> selectByMark(String mark) {
        List<SysCodeDto> sysCodeDtos = sysCodeService.queryListByMark(mark);
        return Response.ok().wrap(sysCodeDtos);
    }

    @GetMapping("selectByMarkValue")
    @Operation(summary = "根据字典标识和字典值查询字典")
    public Response<Object> selectByMarkValue(String mark, String value) {
        SysCodeDto sysCodeDto = sysCodeService.selectOneWithMarkValue(mark, value);
        return Response.ok().wrap(sysCodeDto);
    }

}
